<template>
	<div>
		<div v-show="Login == true">
			<div id="login_container">
				<div id="login_box">
					<!-- 头像 -->
					<div id="avatar_box">
						<img src="../../assets/img/FTP.jpg" />
					</div>

					<!-- 登录表单区域 -->
					<Form :model="loginForm" label-width="0px" id="login_form" style="padding-top:50px">
						<!-- 用户名 -->
						<Form-item>
							<Input v-model="loginForm.host"></Input>
						</Form-item>
						<!-- 密码 -->
						<Form-item>
							<Input v-model="loginForm.username"></Input>
						</Form-item>
						<!-- 密码 -->
						<Form-item>
							<Input v-model="loginForm.password" type="password"></Input>
						</Form-item>
						<!-- 按钮区域 -->
						<Form-item style="text-align: center;">
							<Button @click="GoFTP">连接FTP共享</Button>
						</Form-item>
					</Form>
				</div>

			</div>
		</div>
		<div v-show="Login == false">
			<div style="width: 100%;height: 10vh;">
				<div style="height: 30px;width: 100%;">
					<div style="display: flex;justify-content:space-between;">
						<Row type="flex" justify="start" class="code-row-bg" style="float: left;padding-right: 5px; height: 40px;line-height: 60px;">
							<div style="float:left; margin-left:10px; line-height: 40px;">
								<Button size="small" icon="ios-cloud-upload" @click="UploadDetails">上传</Button>
								<input type="file" style="width: 0px;height: 0px;" id="file" v-show="inputfile" @change="UploadFile" />
								<Button size="small" icon="ios-add-circle" @click="NewFolder = true">新建</Button>
								<Modal title="新建文件夹" v-model="NewFolder" @on-ok="YesFolder" @on-cancel="Nofolder">
									<Input v-model="FolderValue" placeholder="请输入新建文件夹的名称……" style="width: 100%;" />
								</Modal>
								<Button size="small" icon="ios-add-circle" @click="asdfasdfasdf">断开FTP连接</Button>
							</div>
							<div style="margin-left:5px; line-height: 40px;">
								<Button size="small" v-show="!Copy" icon="md-trash" @click="handleContextMenuCopy">粘贴</Button>
								<ButtonGroup>
									<Button size="small" v-show="button" icon="md-trash" @click="Deletes">删除</Button>
									<Button size="small" v-show="button" icon="md-cloud-download" @click="download">下载</Button>
									<Button size="small" v-show="button" icon="ios-copy" @click="Copys">复制到</Button>
									<Button size="small" v-show="button" icon="ios-albums">移动到</Button>
								</ButtonGroup>
							</div>
						</Row>

						<div style="display: flex;align-items: center;">
							<div style="height: 40px;">
								<i-switch size="small" v-model="switch1" @on-change="change" style="margin-top: 12px;float: right;margin-right: 10px;" />
								<Input v-model="SearchValue" suffix="ios-search" size="small" placeholder="搜索" style="margin-top: 7px; width: auto; float: right; margin-right: 10px;"
								 @on-change="sousuo" />
							</div>
						</div>
					</div>
				</div>
				<div style="width: 100%;height: 30px;background: #000099;">
					<div style="height: 50px; background-color: #FFFFFF;">
						<Row type="flex" justify="start" class="code-row-bg" style="float: left; ">
							<div style="height: 50px; line-height: 50px; margin-left: 10px;">
								<a style="color: #3f3f3f;" @click="Back">
									<Icon type="ios-arrow-back" size="20" />
								</a>
								<!-- 返回上一层 -->
								<a style="margin-left: 5px;" @click="Refresh">
									<Icon type="md-refresh" color="#3f3f3f" size="20" />
								</a>

								<Divider type="vertical" size="default" />
							</div>
							<Breadcrumb>
								<a style="height: 50px; line-height: 50px;color: #3f3f3f;" @click="aaaaa(index)" v-for="(item,index) in path">
									<BreadcrumbItem>
										<Icon type="ios-home-outline"></Icon>
										{{item}}
									</BreadcrumbItem>
								</a>
							</Breadcrumb>
						</Row>
					</div>
				</div>
			</div>
			<div></div>
			<div style="width: 100%;height: 76vh;overflow:auto;">
				<Table size="small" :columns="columns1" :data="list" v-if="!switch1" @on-selection-change="select" @on-row-dblclick="dbClick"
				 show-context-menu @on-contextmenu="handleContextMenu">
					<template slot="contextMenu">
						<DropdownItem @click.native="handleContextMenuDownload">下载</DropdownItem>
						<DropdownItem @click.native="NewFile = true">重命名</DropdownItem>
						<Modal title="重命名" v-model="NewFile" @on-ok="YesFile" @on-cancel="NoFile">
							<Input v-model="FileValue" placeholder="请输入重命名的名称……" style="width: 100%;" />
						</Modal>
						<DropdownItem @click.native="handleContextMenuCopy" v-if="Copy == true">复制</DropdownItem>
						<DropdownItem @click.native="handleContextMenuCopy" v-else>粘贴</DropdownItem>
						<DropdownItem @click.native="handleContextMenuDelete" style="color: #ed4014">删除</DropdownItem>
					</template>
				</Table>
				<div v-if="switch1" style="width: 100%;">
					<ul v-for="item in list" style="float: left;margin: 5px;">
						<div id="div" @dblclick="dbClick(item)">
							<img :src="'src/renderer/assets/icon/6.png'" width="60px" height="60px" />
							<h5>{{item.name}}</h5>
						</div>
					</ul>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
	import axios from "axios";
	import qs from "qs";
	const iconv = require('iconv-lite');
	var client = require('ftp');

	var fs = require('fs');

	var c = new client();

	// var connectionProperties = {
	// 	host: this.loginForm.host,
	// 	user: this.loginForm.username,
	// 	password: this.loginForm.password,
	// 	port: 21 //默认是21，这个看自己要连接的端口
	// };


	export default {
		data() {
			return {
				loginForm: {
					host: '106.55.15.51',
					username: 'uftp',
					password: 'zxc123456',
				},
				Login: true,
				list: [], //文件列表
				button: false, //多选显示按钮
				value: "", //新建文件夹的value
				switch1: false, //切换缩略图
				SearchValue: "", //搜索文件value
				Selection: [], //多选按钮事件
				NewFolder: false, //新建文件夹弹窗
				FolderValue: "", //新建文件夹value
				NewFile: false, //新建文件夹弹窗
				FileValue: "", //新建文件夹value
				path: [], //面包屑路径
				ContextMenu: [],
				fsid: [], //fs_id获取下载链接
				download_url: [], //下载链接
				Uploadfiles: [],
				Copy: true, //复制、粘贴文件判断
				CopyFile: [],
				inputfile: false, //上传input框隐藏
				admin: [],
				columns1: [{
						type: "selection",
						width: 60,
						align: "center"
					},
					{
						title: "文件名",
						key: "name"
					},
					{
						title: "文件大小",
						key: "size",
						width: 150,
						align: "center"
					}
				]
			};
		},
		mounted() {
			//获取文件列表
			this.Refresh();
		},
		methods: {
			Refresh() {
				var access_token = window.sessionStorage.getItem("access_token");
				var path = "/" + this.path.join("/");
				axios({
					url: "https://pan.baidu.com/rest/2.0/xpan/file?method=list&access_token=" +
						access_token +
						"&dir=/" +
						path +
						"&start=0&limit=10000&web=web",
					method: "get"
				}).then(respanse => {
					this.list = respanse.data.list;
					if (this.list.length != 0) {
						for (var i = 0; i < this.list.length; i++) {
							//定义空字符串size
							var size = "";
							//获取数组内的size并赋值变量
							var fileSize = this.list[i].size;
							//判断文件大小
							if (fileSize < 1024) {
								size = fileSize + "B";
							} else if (fileSize < 1048576) {
								size = (fileSize / 1024).toFixed(1) + "K";
							} else if (fileSize < 1073741824) {
								size = (fileSize / 1048576).toFixed(1) + "M";
							} else {
								size = (fileSize / 1073741824).toFixed(1) + "G";
							}
							// 将数据重新放入到obj数组里面
							var obj = this.list[i]; //或者 var obj=new Object();
							var key = "size";
							obj[key] = size;
						}
					} else {}
				});
			},

			GoFTP() {
				this.Login = false
			},
			aaaaa(row, index) {
				// 获取点击的名字
				var name = this.path[row];
				console.log(name)
				// 将数组转换字符串
				var Clickpath = this.path.join("/");
				// 截取到点击的路径
				var path = Clickpath.substring(
					0,
					Clickpath.lastIndexOf(name) + name.length
				);
				// 将路径转换成数组
				this.path = path.split("/");
				this.Refresh();
			},
			//刷新文件列表
			Refresh() {
				var connectionProperties = {
		host: this.loginForm.host,
		user: this.loginForm.username,
		password: this.loginForm.password,
		port: 21 //默认是21，这个看自己要连接的端口
	};
				window.sessionStorage.setItem('FTP_path', "/")
				console.log(c.put)
				c.connect(connectionProperties); //连接ftp
				const FTP_path = '/' + this.path.join("/");
				var _this = this;
				//和ftp服务器连接成功后，会进到这里来。接着可以上传下载文件或者做其它事情了。
				c.list(FTP_path, function(err, list) { //Get a directory listing of the current (remote) working directory:
					if (err) throw err;
					var files = list;
					for (var i = 0; i < list.length; i++) {

						files[i].name = iconv.decode(files[i].name, 'utf-8')
					}

					_this.list = files;
					c.end();
				});


			},
			//批量操作
			select(Selection) {
				// 对选中的数据 显示按钮，执行操作

				//将选中的数据，存储到数组里面，以便使用
				this.Selection = Selection;

				if (Selection.length != 0) {
					this.button = true;
				} else {
					this.button = false;
				}
				console.log(Selection);
			},
			//缩略图切换
			change(status) {
				this.$Message.info("开关状态：" + status);
			},
			//搜索文件
			sousuo() {
				
			},
			//tab表格双击事件
			dbClick(row) {
				console.log(row)
				if (row.type == 'd') {
					//更改面包屑
					console.log(row.name); //文件夹名称
					this.path.splice(this.path.length, 0, row.name);
					//进入子目录
					this.Refresh();
					console.log(this.path);
				} else {

				}
			},
			//确定新建文件夹
			YesFolder() {
				var connectionProperties = {
		host: this.loginForm.host,
		user: this.loginForm.username,
		password: this.loginForm.password,
		port: 21 //默认是21，这个看自己要连接的端口
	};
				var value = this.FolderValue;
				// var access_token = window.sessionStorage.getItem("access_token");
				var path = "/" + this.path.join("/");
				path = path + "/" + value;
				c.connect(connectionProperties); //连接ftp
				c.mkdir(path, function(err, data) {
					console.log(err)
					if (err) throw err;

					c.end(); //关闭
					setTimeout(function() {
						this.Refresh();
					}, 500);
				});
			},
			//取消新建文件夹
			Nofolder() {
				// this.$Message.warning("已取消新建文件夹！");
			},
			//批量删除
			Deletes() {

				this.$Modal.confirm({
					title: "温馨提示",
					content: "<p>是否需要删除该文件？</p>",
					onOk: () => {
						console.log(this.Selection);
						var Selection = this.Selection
						var _this = this;
						for (var i = 0; i < Selection.length; i++) {
							var path = this.path.join("/");
							path = path + '/' + this.Selection[i].name
							if (this.Selection[i].name.indexOf(".") != -1) {
								var connectionProperties = {
		host: this.loginForm.host,
		user: this.loginForm.username,
		password: this.loginForm.password,
		port: 21 //默认是21，这个看自己要连接的端口
	};
								//文件
								c.connect(connectionProperties); //连接ftp
								c.delete(path, function(err) {
									if (err) throw err;
									c.end(); //关闭
									// _this.$Message.success("删除文件成功！");
									if (i == (Selection.length - 1)) {
										setTimeout(function() {
											_this.Refresh();
										}, 500);
									}

								});
							} else {
								var connectionProperties = {
		host: this.loginForm.host,
		user: this.loginForm.username,
		password: this.loginForm.password,
		port: 21 //默认是21，这个看自己要连接的端口
	};
								//文件夹
								c.connect(connectionProperties); //连接ftp
								c.rmdir(path, function(err) {
									if (err) throw err;
									c.end(); //关闭
									// _this.$Message.success("删除文件夹成功！");
									if (i == (Selection.length - 1)) {
										setTimeout(function() {
											_this.Refresh();
										}, 500);
									}


								});
							}


						}
						this.$Message.success("删除所选文件成功！");

						setTimeout(function() {
							_this.Refresh();
						}, 500);
					},
					onCancel: () => {
						this.$Message.info("Clicked cancel");
					}
				});
			},
			// 批量复制粘贴
			Copys() {
				// var Selection = this.Selection;
				// console.log(Selection);
				// for (var i = 0; i < Selection.length; i++) {
				// 	var path = "/" + this.path.join("/");
				// 	var access_token = window.sessionStorage.getItem("access_token");
				// 	var name = Selection[i].server_filename;
				// 	axios({
				// 		url: "https://pan.baidu.com/rest/2.0/xpan/file?method=filemanager&access_token=" +
				// 			access_token +
				// 			"&opera=copy",
				// 		method: "post",
				// 		data: qs.stringify({
				// 			async: 2,
				// 			filelist: '[{"path":"/' +
				// 				name +
				// 				'","dest":"/1","newname":"' +
				// 				name +
				// 				'","ondup":"overwrite"}]'
				// 		})
				// 	}).then(res => {
				// 		console.log(res);
				// 		this.$Message.success(
				// 			"粘贴文件：" + this.CopyFile.server_filename + "成功！"
				// 		);
				// 		// 刷新页面
				// 		this.Refresh();
				// 	});
				// }
			},
			// 返回上一层
			Back() {
				//判断是否为根目录
				if (this.path.length == 0) {
					//alert('123123213')
					// this.$router.push("/Netdisc");
				}
				//当前目录-1
				this.path.splice(-1, 1);
				//刷新目录
				this.Refresh();
			},
			// 右键点击事件
			handleContextMenu(row) {
				this.ContextMenu = row;
				this.FileValue = row.name;
			},
			// 确定重命名
			YesFile() {
				var value = this.FileValue;
				var name = this.ContextMenu.name;
				var path = "/" + this.path.join("/");
				value = path + "/" + value
				path = path + "/" + name;
				var _this = this;
				// console.log('Value:'+value)
				// console.log('name:'+name)
				// console.log('path:'+path)
				var connectionProperties = {
		host: this.loginForm.host,
		user: this.loginForm.username,
		password: this.loginForm.password,
		port: 21 //默认是21，这个看自己要连接的端口
	};
				c.connect(connectionProperties); //连接ftp
				c.rename(path, value, function(err) {
					if (err) throw err;
					c.end(); //关闭
					setTimeout(function() {
						_this.Refresh();
					}, 500);
				});


				// axios({
				// 	url: "https://pan.baidu.com/rest/2.0/xpan/file?method=filemanager&opera=rename&access_token=" +
				// 		access_token,
				// 	method: "post",
				// 	data: qs.stringify({
				// 		async: "2",
				// 		filelist: '[{"path":"' + path + '","newname":"' + value + '"}]'
				// 	})
				// }).then(res => {
				// 	this.$Message.success("重命名：" + value);
				// 	var _this = this;
				// 	setTimeout(function() {
				// 		_this.Refresh();
				// 	}, 500);
				// });
			},
			// 取消重命名
			NoFile() {
				this.$Message.warning("已取消重命名！");
			},
			// 上传文件
			UploadDetails() {
				document.getElementById('file').click()
			},
			UploadFile(files) {
				
				var path = document.getElementById('file').files[0].path
				var name = document.getElementById('file').files[0].name
				console.log(document.getElementById('file').files[0])
				c.put(path, '/public/' + name, function(err, data) {
					console.log(data)
					console.log(err)
					if (err) throw err;
					c.end();
						
				});
			},
			// 获取上传进度条
			sadfasdf(event, file, fileList) {
				// console.log(file.percentage);
				// console.log(file.name);
				// // 打开上传详细
				// this.UploadDetails = true;
				// // 把详细资料添加到数组
				// this.Uploadfiles = file;
				// // 上传成功 Buuton不展开
				// this.button = false;
				// // 成功提示
				// if (file.percentage == 100) {
				// 	this.$Message.success("上传" + file.name + "成功");
				// }
			},
			// 右键菜单删除
			handleContextMenuDelete() {
				var _this = this;
				this.$Modal.confirm({
					title: "温馨提示",
					content: "<p>是否需要删除该文件？</p>",
					onOk: () => {
						var name = this.ContextMenu.name;
						var path = "/" + this.path.join("/");
						path = path + "/" + name;
						var ck = name.indexOf(".");
						if (name.indexOf(".") != -1) {
							var connectionProperties = {
		host: this.loginForm.host,
		user: this.loginForm.username,
		password: this.loginForm.password,
		port: 21 //默认是21，这个看自己要连接的端口
	};
							//文件
							c.connect(connectionProperties); //连接ftp
							c.delete(path, function(err) {
								if (err) throw err;
								c.end(); //关闭
								_this.$Message.success("删除文件成功！");
								setTimeout(function() {
									_this.Refresh();
								}, 500);

							});
						} else {
							var connectionProperties = {
		host: this.loginForm.host,
		user: this.loginForm.username,
		password: this.loginForm.password,
		port: 21 //默认是21，这个看自己要连接的端口
	};
							//文件夹
							c.connect(connectionProperties); //连接ftp
							c.rmdir(path, function(err) {
								if (err) throw err;
								c.end(); //关闭
								_this.$Message.success("删除文件夹成功！");
								setTimeout(function() {
									_this.Refresh();
								}, 500);

							});
						}

						// //刷新目录
						//_this.Refresh();
					},
					onCancel: () => {
						this.$Message.info("Clicked cancel");
					}
				});
			},
			// 批量下载文件
			download() {
				// var access_token = window.sessionStorage.getItem("access_token");
				// // 获取选中的文件
				// var Selection = this.Selection;
				// // 把fsid 放在一个数组里面
				// for (var i = 0; i < Selection.length; i++) {
				// 	console.log(i);
				// 	this.fsid.splice(this.fsid.length, 0, Selection[i].fs_id);
				// }
				// // 把fsid数组里面的数据拆分成一个字符串并用,号分开
				// var Clickpath = this.fsid.join(",");
				// // 获取选中文件的dink  下载链接
				// axios({
				// 	url: "https://pan.baidu.com/rest/2.0/xpan/multimedia?method=filemetas&access_token=" +
				// 		access_token +
				// 		"&fsids=[" +
				// 		Clickpath +
				// 		"]&dlink=1",
				// 	method: "get"
				// }).then(res => {
				// 	// 先把返回的数组放到download_url数组里面
				// 	var download_url = res.data.list;
				// 	// 循环下载链接   并通过aria2  下载文件
				// 	for (var i = 0; i < this.fsid.length; i++) {
				// 		const download =
				// 			download_url[i].dlink + "&access_token=" + access_token;
				// 		axios({
				// 			url: "http://127.0.0.1:6800/jsonrpc",
				// 			method: "post",
				// 			crossDomain: true,
				// 			processData: false,
				// 			data: JSON.stringify({
				// 				id: "",
				// 				jsonrpc: "2.0",
				// 				method: "aria2.addUri",
				// 				params: [
				// 					"token:kumao",
				// 					[download],
				// 					{
				// 						"download-result": "full",
				// 						header: "User-Agent:pan.baidu.com",
				// 						out: download_url[i].filename
				// 					}
				// 				]
				// 			}),
				// 			headers: {
				// 				contentType: "application/json"
				// 			}
				// 		}).then(res => {});
				// 	}
				// 	this.$Message.success("已将选中文件，添加到下载队列！");
				// });
			},
			// 右键菜单下载
			handleContextMenuDownload() {
				// var access_token = window.sessionStorage.getItem("access_token");
				// console.log(this.ContextMenu);
				// const fsid = this.ContextMenu.fs_id;
				// axios({
				// 	url: "https://pan.baidu.com/rest/2.0/xpan/multimedia?method=filemetas&access_token=" +
				// 		access_token +
				// 		"&fsids=[" +
				// 		fsid +
				// 		"]&dlink=1",
				// 	method: "get"
				// }).then(res => {
				// 	console.log(res);

				// 	// 先把返回的数组放到download_url数组里面
				// 	var download_url =
				// 		res.data.list[0].dlink + "&access_token=" + access_token;

				// 	// 循环下载链接   并通过aria2  下载文件
				// 	axios({
				// 		url: "http://127.0.0.1:6800/jsonrpc",
				// 		method: "post",
				// 		crossDomain: true,
				// 		processData: false,
				// 		data: JSON.stringify({
				// 			id: "",
				// 			jsonrpc: "2.0",
				// 			method: "aria2.addUri",
				// 			params: [
				// 				"token:kumao",
				// 				[download_url],
				// 				{
				// 					"download-result": "full",
				// 					header: "User-Agent:pan.baidu.com",
				// 					out: res.data.list[0].filename
				// 				}
				// 			]
				// 		}),
				// 		headers: {
				// 			contentType: "application/json"
				// 		}
				// 	}).then(res => {});
				// 	this.$Message.success("已将选中文件，添加到下载队列！");
				// });
			},
			// 右键菜单复制
			handleContextMenuCopy() {
				// 	// 判断当前状态是复制还是粘贴
				// 	if (this.Copy == true) {
				// 		this.CopyFile = this.ContextMenu;
				// 		this.$Message.success(
				// 			"复制文件：" + this.CopyFile.server_filename + "成功！"
				// 		);
				// 		this.Copy = !this.Copy;
				// 	} else {
				// 		var path = "/" + this.path.join("/");
				// 		var access_token = window.sessionStorage.getItem("access_token");
				// 		var name = this.CopyFile.server_filename;
				// 		axios({
				// 			url: "https://pan.baidu.com/rest/2.0/xpan/file?method=filemanager&access_token=121.e2e1716b54932e6062722d0bbcaeda55.YgHZHw6vmiil8Mwtf0vN8m8UHpbD70dL0H-qA8e.QIKmOg&opera=copy",
				// 			method: "post",
				// 			data: qs.stringify({
				// 				async: 2,
				// 				filelist: '[{"path":"/' +
				// 					name +
				// 					'","dest":"' +
				// 					path +
				// 					'","newname":"' +
				// 					name +
				// 					'","ondup":"overwrite"}]'
				// 			})
				// 		}).then(res => {
				// 			console.log(res);
				// 			this.$Message.success(
				// 				"粘贴文件：" + this.CopyFile.server_filename + "成功！"
				// 			);
				// 			// 刷新页面
				// 			this.Refresh();
				// 		});
				// 		this.Copy = !this.Copy;
				// 	}
				// },

			},
			asdfasdfasdf() {
				this.Login = true
			},

		}
	}
</script>

<style>
	.ul-li {
		float: left;
		text-align: center;
		list-style: none;
		width: 100px;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		transition: .5s;
		margin: 5px;
	}

	.ul-li:hover {
		background-color: #e5f3ff;
		transform: translateY(-5px);
	}

	#disk ul ul li {
		height: 25px;
	}

	.div {
		width: 100px;
		height: 100px;
		text-align: center;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.div:hover {
		transform: translateY(-5px);
		background-color: #0275D8;
	}

	#login_container {
		background-color: #2b4b6b;
		height: 100%;
	}

	#login_box {
		width: 450px;
		height: 300px;
		background-color: #fff;
		border-radius: 3px;
		position: absolute;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
	}

	#avatar_box {
		height: 130px;
		width: 130px;
		border: 1px solid #eee;
		border-radius: 50%;
		padding: 10px;
		box-shadow: 0 0 10px #ddd;
		position: absolute;
		left: 50%;
		transform: translate(-50%, -50%);


	}

	#avatar_box img {
		width: 100%;
		height: 100%;
		border-radius: 50%;
		background-color: #eee;
	}

	#login_form {
		position: absolute;
		bottom: 0;
		width: 100%;
		padding: 0 20px;
		box-sizing: border-box;
	}



	#btn {
		display: flex;
		justify-content: flex-end;
	}
</style>
